//
//  FirstSearchController.m
//  MedicineBox
//
//  Created by dllo on 15/9/18.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "FirstSearchController.h"
#import "HomeModel.h"
#import "DKNightVersion.h"
#import "AsyncConnection.h"
#import "DrugListViewController.h"
#import "CompanyViewController.h"
#import "SearchTableView.h"
#import "SearchListController.h"
@interface FirstSearchController ()<UITableViewDataSource,UITableViewDelegate,UISearchBarDelegate>

{
    NSInteger _count;
}

@property (nonatomic, retain) UINavigationController *navC;
@property (nonatomic, retain) UITabBarController *tabC;
@property (nonatomic, assign) NSInteger colorCount;
@property (nonatomic, assign) BOOL value;
@property (nonatomic, retain) SearchTableView *secondShow;
@property (nonatomic, retain) NSMutableArray *secondArray;
@property (nonatomic, retain) NSArray *tempArray;

@property (nonatomic, retain) NSString *searchString;
@property (nonatomic, retain) UISearchBar *mySearchBar;

@property (nonatomic, retain) UITableView *tableV;

@property (nonatomic, retain) NSMutableArray *searchArray;
@end

@implementation FirstSearchController


-(void)dealloc
{
    
   
    [_navC release];
    [_tabC release];
    [_searchArray release];
    [_mySearchBar release];
    [_searchString release];
    [_secondShow release];
    [_tableV release];
    
    [super dealloc];
}

- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        self.searchArray = [NSMutableArray array];
        self.secondArray = [NSMutableArray array];
        self.tableV.nightBackgroundColor = UIColorFromRGB(0x343434);
        self.tableV.nightSeparatorColor =[UIColor whiteColor];
        [DKNightVersionManager addClassToSet:self.class];
        [_tableV release];
       
            
   
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.tableV = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2 - 70, self.view.frame.size.height) style:UITableViewStylePlain];
    self.tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableV.delegate = self;
    self.tableV.dataSource = self;
    [self.view addSubview:self.tableV];
    _tableV.nightBackgroundColor = UIColorFromRGB(0x343434);
   
    
    self.secondShow = [[SearchTableView alloc] initWithFrame:CGRectMake(self.view.frame.size.width / 2 - 70, 0, self.view.frame.size.width - (self.view.frame.size.width / 2 - 70), self.view.frame.size.height - 60) style:UITableViewStyleGrouped];
    _secondShow.nightBackgroundColor = UIColorFromRGB(0x343434);
    _secondShow.nightSeparatorColor = UIColorFromRGB(0x313131);
    [self.view addSubview:_secondShow];
    _secondShow.target = self;
    _secondShow.action = @selector(tapAction:);
    [_secondShow release];
    _colorCount = 0;
    _value = YES;
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    view.backgroundColor = [UIColor clearColor];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.titleView = view;
    [view release];
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(0, 5, 20, 20);
    [backButton setImage:[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"iconfont-fanhui-3" ofType:@"png"]] forState:UIControlStateNormal];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:backButton];
    
    self.mySearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(30, 0, self.view.frame.size.width - 120, 40)];
    _mySearchBar.delegate = self;
    _mySearchBar.layer.cornerRadius = 5;
    _mySearchBar.barStyle = UIBarStyleDefault;
    _mySearchBar.keyboardType = UIKeyboardTypeDefault;
    _mySearchBar.searchBarStyle = UISearchBarIconSearch;
   
    [view addSubview:_mySearchBar];
    
    _mySearchBar.placeholder = @"请输入药名或疾病名";
    [_mySearchBar release];
  
    
    [AsyncConnection asyncConnectionWithUrl:@"http://mobi.111.com.cn/ApiControl?method=products.category.getsecondcategory&method=products.category.getsecondcategory&categoryversion=2&searchtype=2&fatherid=99&categorytype=2&encryptversion=2&sign=7ADE0E7F71942EDB86A995F28F6ABCEC&timestamp=20150919131225&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854" name:@"nextSearchFile" parameters:nil block:^(id data) {
        
        NSArray *array = [[data objectForKey:@"data"] objectForKey:@"categoryinfo"];
        [_secondShow getArray:array title:nil];
        
        
    } get:@"post"];
   
    
}

- (void)getArray:(NSArray *)searchArray
{

    [_searchArray removeAllObjects];
    _tempArray = searchArray;
    [_searchArray addObjectsFromArray:searchArray];
    

}

- (void)tapAction:(NSDictionary *)dic
{

    NSString *catalogId = [dic objectForKey:@"content"];
    NSArray *array = [catalogId componentsSeparatedByString:@"="];
    catalogId = [array objectAtIndex:1];
    NSString *url = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.getlist.news&method=products.getlist.news&isDesc=1&sort=0&province=9&pageindex=1&pagesize=10&catalogId=%@&encryptversion=2&sign=5BEBF94B15FB772D6547C140CF097F45&timestamp=20150918190421&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",catalogId];
    SearchListController *listC = [[SearchListController alloc] init];
    [listC getTab:self.tabC nav:self.navC];
    [listC getUrl:url dic:dic];
    [self.navigationController pushViewController:listC animated:YES];
    [listC release];

}

- (void)backButtonAction:(id)sender
{

    [self.navigationController popViewControllerAnimated:YES];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.searchArray.count;
}

#warning 第一处发现
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *key = @"haha";
    UITableViewCell  *cell = [tableView dequeueReusableCellWithIdentifier:key];
    if (!cell) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:key] autorelease];
    }
    cell.nightBackgroundColor = UIColorFromRGB(0x343434);
    
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    if (_value == NO) {
        
        NSMutableAttributedString *att = [self changeStringColor:[[self.searchArray objectAtIndex:indexPath.row] showname]];
        cell.textLabel.attributedText = att;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ 个药品信息", [[self.searchArray objectAtIndex:indexPath.row] recordcount]];
        
    } else if (_value == YES) {
    
        cell.textLabel.text = [[_searchArray objectAtIndex:indexPath.row] objectForKey:@"name"];
        cell.textLabel.font = [UIFont systemFontOfSize:10];
        cell.textLabel.textColor = [UIColor blackColor];
        cell.detailTextLabel.text = @"";
        cell.textLabel.nightTextColor = [UIColor whiteColor];
        if (indexPath.row == _colorCount) {
            
            cell.backgroundColor = [UIColor whiteColor];
            cell.nightBackgroundColor = [UIColor grayColor];
            
        } else {
        
            cell.backgroundColor = [UIColor colorWithWhite:0.9 alpha:1];
            cell.nightBackgroundColor = UIColorFromRGB(0x343434);
        
        }
        
    }
   
    cell.textLabel.nightTextColor = [UIColor whiteColor];
    cell.detailTextLabel.nightTextColor = [UIColor whiteColor];
    return cell;
}


#pragma mark -
#pragma mark 关键字高亮

- (NSMutableAttributedString *)changeStringColor:(NSString *)string
{
    
    NSMutableAttributedString *changStr = [[NSMutableAttributedString alloc] initWithString:string];
    if (string.length >= self.searchString.length) {
        for (int i = 0; i < string.length - self.searchString.length + 1; i++) {
            if ([[string substringWithRange:NSMakeRange(i, self.searchString.length)] isEqualToString:self.searchString]) {
                NSRange range = NSMakeRange(i, self.searchString.length);
                [changStr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range.location,range.length)];
            }
        }
    }
    return changStr;
}
#pragma mark -
#pragma mark 点击搜索列表的事件 通过协议回调
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (_value == NO) {
        
        if (self.searchArray.count > 0) {
            
            DrugListViewController *search = [[DrugListViewController alloc] init];
            HomeModel *model = [_searchArray objectAtIndex:indexPath.row];
            search.word = model.showname;
            [self presentViewController:search animated:YES completion:nil];
            [search release];
            
            
        }

    } else if (_value == YES) {
    
        _colorCount = indexPath.row;
        [self.tableV reloadData];
        
        
        NSString *searchId = [[_searchArray objectAtIndex:indexPath.row] objectForKey:@"id"];
        NSString *searchUrl = [NSString stringWithFormat:@"http://mobi.111.com.cn/ApiControl?method=products.category.getsecondcategory&method=products.category.getsecondcategory&categoryversion=2&searchtype=2&fatherid=%@&categorytype=2&encryptversion=2&sign=7ADE0E7F71942EDB86A995F28F6ABCEC&timestamp=20150919131225&os=android&venderId=2011102716210000&signmethod=md5&format=json&type=mobile&channelName=huawei&versionName=4.6.1&versionCode=477&screensize=480*854&width=480&height=854",searchId];
        [AsyncConnection asyncConnectionWithUrl:searchUrl name:@"nextSearchFile" parameters:nil block:^(id data) {
            
            NSArray *array = [[data objectForKey:@"data"] objectForKey:@"categoryinfo"];
        
            [_secondShow getArray:array title:[[_searchArray objectAtIndex:indexPath.row] objectForKey:@"subtitle"]];
            
            
        } get:@"post"];

    }
    
}




- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    _value = NO;
    [self.searchArray removeAllObjects];
    _tableV.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    _tableV.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
    _secondShow.frame = CGRectMake(0, 0, 0, 0);
    NSString *word = [searchText stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //搜索列表
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    [dic setObject:@"app" forKey:@"app_key"];
    [dic setObject:@"9DFAAD5404FCB6168EA6840DCDFF39E5" forKey:@"sign"];
    [dic setObject:word forKey:@"key"];
    [AsyncConnection asyncConnectionWithUrl:MB_SearchList name:nil parameters:dic block:^(id data) {
        NSArray *results = [data objectForKey:@"results"];
        for (NSDictionary *dic in results) {
            HomeModel *model = [[HomeModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.searchArray addObject:model];
            if (_searchArray.count > 0) {
                
                [self.tableV reloadData];
                
            }
        }
       
    } get:@"get"];
    
}
/**
 *
 *
 *  @param searchBar 搜索完把 取消按钮隐藏
 */
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
    searchBar.text = @"";
}
/**
 *  点击取消事件
 *
 *  @param searchBar 把创建的view移除掉 并把数组里数据删除 下次搜索不在出现
 并且searchBar 失去响应即键盘回收
 */
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    _value = YES;
    [_searchArray removeAllObjects];
    [_searchArray addObjectsFromArray:_tempArray];
    
    self.tableV.frame = CGRectMake(0, 0, self.view.frame.size.width / 2 - 70, self.view.frame.size.height);
    _tableV.separatorStyle = UITableViewCellSeparatorStyleNone;
     self.secondShow.frame = CGRectMake(self.view.frame.size.width / 2 - 70, 0, self.view.frame.size.width - (self.view.frame.size.width / 2 - 70), self.view.frame.size.height);
    [self.tableV reloadData];
    [searchBar resignFirstResponder];
    _count = 0;
}
/**
 *  搜索按钮
 *
 *  @param searchBar 点击搜索按钮事件
 */
-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    
    if (self.searchArray.count == 0) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"没有相关的数据" preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction *ok = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
            
        }];
        [alert addAction:ok];
        [self presentViewController:alert animated:YES completion:nil];
    }
    else
    {
        DrugListViewController *search = [[DrugListViewController alloc] init];
        search.word = searchBar.text;
        [self presentViewController:search animated:YES completion:nil];
        [search release];
        
    }
    
}

/**
 *  协议回调
 *
 *  @param model 返回model 进入药品列表
 */
- (void)valueWithModel:(HomeModel *)model
{
    DrugListViewController *search = [[DrugListViewController alloc] init];
    search.word = model.showname;
    [self presentViewController:search animated:YES completion:nil];
    [search release];
  
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    
    searchBar.showsCancelButton = YES;
    return YES;
}

- (void)getTabC:(UITabBarController *)tab nav:(UINavigationController *)nav
{

    self.tabC = tab;
    self.navC = nav;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
